/* 
 * Copyright [2018] [Alex/libo(liboms@hotmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.aop.handler.reflection;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.logging.Logger;

import com.hyts.aop.annotation.Before;
import com.hyts.aop.annotation.Ignore;
import com.hyts.aop.annotation.Weave;
import com.hyts.aop.bean.ProcessArg;
import com.hyts.aop.error.AopException;
import com.hyts.aop.handler.base.BeforeMethod;

/**
 * @title BeforeAopHandler.java
 * @package com.hyts.aop.handler.java
 * @author libo/Alex
 * @email liboms@hotmail.com/liboware@163.com
 * @date 2018年4月25日
 * @version V1.0
 */
public class BeforeMethodHandler extends BeforeMethod{

	/**
	 * <p>
	 * {字段的描述}
	 * </p>
	 * 
	 * @fieldName logger
	 * @fieldType Logger
	 */
	Logger logger = Logger.getLogger(BeforeMethodHandler.class.getName());

	
	private Map<Object,Method[]> methodList;
	

	/**  
	 * @constructor：BeforeMethodHandler  
	 * @param proxyRealObject
	 */ 
	public BeforeMethodHandler(Object... proxyRealObject) {
		super();
		methodList = new LinkedHashMap<>();
		for(Object param:proxyRealObject){
			methodList.put(param,param.getClass().getMethods());
		}
	}
	
	/**  
	 * @throws IllegalAccessException
	 * @throws IllegalArgumentException
	 * @throws InvocationTargetException
	 * @exception
	 */ 
	public void before(Object... params)  {
		//方法执行列表
		try {
			Set<Map.Entry<Object,Method[]>> methodData = methodList.entrySet();
				for(Map.Entry<Object,Method[]> methodElement:methodData) {
					for (int i = 0; i < methodElement.getValue().length; i++) {
						if (!methodElement.getValue()[i].isAnnotationPresent(Ignore.class)) {
							if (methodElement.getValue()[i].isAnnotationPresent(Before.class)) {
								Method beforeMethod = methodElement.getValue()[i];
								if(beforeMethod.getParameters() == null || beforeMethod.getParameterCount() == 0){
									beforeMethod.invoke(methodElement.getKey());
								}else {
									ProcessArg processArg = new ProcessArg(params);
									beforeMethod.invoke(methodElement.getKey(),processArg);
								}
								/*if(beforeMethod.getParameterCount()>0){

								}else{
									beforeMethod.invoke(methodElement.getKey());
								}*/
							}
						}
					}
				}
		} catch (IllegalAccessException |InvocationTargetException e) {
		    throw new AopException(e);
		}
	}
}
